<template>
  <div>
    <el-form
      label-position="top"
      :rules="uiState.rules"
      :model="container"
      :disabled="readonly"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            :label="$t('business.workload.container_name')"
            prop="name"
          >
            <ko-data-item
              v-model="container.name"
              itemType="input"
              class="w-full"
              :default="'container-' + randStr()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('business.workload.pull_policy')"
            prop="imagePullPolicy"
          >
            <ko-data-item
              v-model="container.imagePullPolicy"
              class="w-full"
              itemType="select"
              :noClear="true"
              :selections="uiState.image_pull_policy_list"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item :label="$t('business.workload.list_image')">
            <el-select v-model="imageRepo" style="width: 100%">
              <template #header>
                <el-button
                  icon="Plus"
                  size="small"
                  class="w-full"
                  link
                  @click="shouldGotoCreateSecret"
                >
                  <span>新建镜像仓库</span>
                </el-button>
              </template>
              <el-option
                :value="''"
                :label="$t('business.workload.repo_disabled')"
              />
              <el-option
                v-for="(item, index) in imageRepoList"
                :key="index"
                :value="item.secretName"
                :label="`${item.host}(${item.userName})`"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item
            :label="$t('business.workload.container_image')"
            prop="image"
            :rules="uiState.rules.required"
          >
            <ko-data-item
              v-model="container.image"
              placeholder="e.g. nginx:latest"
              itemType="input"
              class="w-full"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="imageRepo !== ''" :gutter="20" style="margin-left: 2px">
        <el-checkbox v-model="uiState.checkImage">
          {{ $t("business.workload.repo_help") }}
        </el-checkbox>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import {
  Container,
  ObjectMeta,
  PodSpec,
  PresetAnnotationKey,
  Secret,
  SecretDataDockerConfig,
  SecretDataKey
} from "../../../api/k8s";
import { ImageRepoItem, WorkloadEditContainerType } from "./types";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useFormRule } from "../../../utils/rules";
import { decodeFromBase64 } from "@/utils/text";
import { useVerifyRouter } from "@/router/use";
import { KRouteSecret } from "../../../router";
import { randStr } from "../../../utils";

// import Rule from "@/utils/rules";
// import { getRepo, listImages } from "../../../../kubepi/src/api/imagerepos";

const { CommonNameRule, RequiredRule, SelectRule } = useFormRule();
const router = useVerifyRouter();

type Prop = {
  containerType?: WorkloadEditContainerType;
  secretList?: Secret[];
  // repoList?: ImageRepoItem[];
  readonly?: boolean;
};

const props = defineProps<Prop>();
const metadata = defineModel<ObjectMeta>("metadata");
const container = defineModel<Container>("container", { default: {} });

const editFormRef = ref();
const uiState = reactive({
  checkImage: false,
  rules: {
    name: [CommonNameRule],
    required: [RequiredRule],
    select: [SelectRule]
  },
  image_pull_policy_list: [
    { label: "Always", value: "Always" },
    { label: "IfNotPresent", value: "IfNotPresent" },
    { label: "Never", value: "Never" }
  ]
});

// 已绑定的容器仓库: {containerName: secretName}
const containerRepo = ref<Record<string, string>>({});

//
type ImageRepoSecret = {
  host: string;
  secretName: string;
  userName: string;
};
const imageRepoList = ref<ImageRepoSecret[]>([]);

const shouldGotoCreateSecret = () => {
  router.push({
    name: KRouteSecret.Create.name
  });
};

const _imageRepo = ref("");
const imageRepo = computed({
  get() {
    return _imageRepo.value;
  },
  set(val) {
    containerRepo.value[container.value.name] = val;
    _imageRepo.value = val;
  }
});

const onMetadataChange = () => {
  containerRepo.value = JSON.parse(
    metadata.value?.annotations?.[PresetAnnotationKey.ImagePullSecret] || "{}"
  );
};

const onSecretListChanged = () => {
  imageRepoList.value =
    (
      props.secretList?.flatMap(secret => {
        const dockerDataBase64 = secret.data?.[SecretDataKey.DockerConfigJson];
        if (dockerDataBase64) {
          const dockerDataUtf8 = decodeFromBase64(dockerDataBase64);
          const dockerAuths = JSON.parse(
            dockerDataUtf8 ?? "{}"
          ) as SecretDataDockerConfig;

          return Object.keys(dockerAuths.auths)
            .map(host => ({
              host,
              secretName: secret.metadata.name,
              userName: dockerAuths.auths[host].username
            }))
            .filter(item => item && item.host);
        }
      }) ?? []
    ).filter(item => item) ?? [];
};

watch(
  () => metadata.value,
  (ov, nv) => {
    if (ov !== nv) {
      onMetadataChange();
    }
  }
);

watch(
  () => props.secretList,
  (ov, nv) => {
    if (ov !== nv) {
      onSecretListChanged();
    }
  }
);

onMounted(() => {
  onMetadataChange();
  onSecretListChanged();
  _imageRepo.value = containerRepo.value[container.value.name] ?? "";
});
</script>
